from django.db import models
from django.contrib.auth.models import AbstractUser
from user.models import User  # 确保导入了 User 模型



# 商品分类模型
class ProductCategory(models.Model):
    name = models.CharField(max_length=100)
    parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='subcategories')

    def __str__(self):
        return self.name


# 商品模型
class Product(models.Model):
    product_code = models.CharField(max_length=20, unique=True, verbose_name='商品编码')
    name = models.CharField(max_length=100, verbose_name='商品名称')
    description = models.TextField(verbose_name='商品描述', null=True, blank=True)
    price = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='销售价格')
    cost_price = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='成本价格')
    stock = models.IntegerField(default=0, verbose_name='库存数量')
    min_stock = models.IntegerField(default=0, verbose_name='最低库存')
    specification = models.CharField(max_length=255, verbose_name='规格', null=True, blank=True)
    unit = models.CharField(max_length=20, verbose_name='计量单位')
    shelf_life_end_date = models.DateField(null=True, verbose_name='保质期截止日期')
    image_url = models.CharField(max_length=255, null=True, verbose_name='图片地址')
    barcode = models.CharField(max_length=50, null=True, blank=True, verbose_name='条形码')
    category = models.ForeignKey(ProductCategory, on_delete=models.CASCADE, related_name='products')

    def __str__(self):
        return self.name


# 库存预警模型
class StockWarning(models.Model):
    WARNING_TYPES = (
        ('stock', '库存不足'),
        ('expiry', '保质期预警'),
    )

    product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='warnings')
    warning_type = models.CharField(max_length=10, choices=WARNING_TYPES)
    threshold = models.IntegerField()
    is_enabled = models.BooleanField(default=True)

    def __str__(self):
        return f"{self.product.name} - {self.get_warning_type_display()}"


# 采购模型
class Purchase(models.Model):
    product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='purchases')
    supplier = models.CharField(max_length=100, verbose_name='供应商')
    purchase_price = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='采购价格')
    purchase_quantity = models.IntegerField(verbose_name='采购数量')
    purchase_time = models.DateTimeField(auto_now_add=True, verbose_name='采购时间')

    def __str__(self):
        return f"{self.product.name} - {self.supplier}"


# 入库模型
class StockIn(models.Model):
    product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='stock_ins')
    batch_number = models.CharField(max_length=50, verbose_name='批次号')
    purchase = models.ForeignKey(Purchase, on_delete=models.SET_NULL, null=True, related_name='stock_ins')
    in_price = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='入库单价')
    in_quantity = models.IntegerField(verbose_name='入库数量')
    in_time = models.DateTimeField(auto_now_add=True, verbose_name='入库时间')

    def __str__(self):
        return f"{self.product.name} - {self.batch_number}"


# 出库模型
class StockOut(models.Model):
    OUT_CHANNELS = (
        ('order', '购物车订单'),
        ('damage', '报损'),
        ('inventory', '盘点'),
    )

    product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='stock_outs')
    out_quantity = models.IntegerField(verbose_name='出库数量')
    out_time = models.DateTimeField(auto_now_add=True, verbose_name='出库时间')
    out_channel = models.CharField(max_length=10, choices=OUT_CHANNELS, verbose_name='出库渠道')
    order = models.ForeignKey('Order', on_delete=models.SET_NULL, null=True, related_name='stock_outs')

    def __str__(self):
        return f"{self.product.name} - {self.get_out_channel_display()}"


# 订单模型
class Order(models.Model):
    STATUS_CHOICES = (
        ('placed', '已下单'),
        ('shipped', '已发货'),
        ('transit', '运输中'),
        ('delivered', '已签收'),
        ('cancelled', '已取消'),
    )

    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='orders')
    order_number = models.CharField(max_length=50, unique=True, verbose_name='订单编号')
    logistics_number = models.CharField(max_length=50, null=True, verbose_name='物流单号')
    order_time = models.DateTimeField(auto_now_add=True, verbose_name='下单时间')
    settlement_time = models.DateTimeField(null=True, verbose_name='结算时间')
    total_amount = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='订单总金额')
    status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='placed', verbose_name='订单状态')
    cart = models.ForeignKey('cart.Cart', on_delete=models.SET_NULL, null=True, related_name='orders')

    def __str__(self):
        return self.order_number
        
    def save(self, *args, **kwargs):
        if self.status == 'delivered' and not self.settlement_time:
            self.settlement_time = timezone.now()
            # Update inventory and create sales records
            for item in self.cart.items.all():
                # Reduce stock
                item.product.stock -= item.quantity
                item.product.save()
                
                # Create stock out record
                StockOut.objects.create(
                    product=item.product,
                    out_quantity=item.quantity,
                    out_channel='order',
                    order=self
                )
        super().save(*args, **kwargs)